package com.sms.graduate.utils;

import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;


/**
 * Thread Pool tools.
 *
 * @author e-zhangjiawei01
 * @since 1.0.0
 */
public abstract class ThreadPoolHelper {

    private static final int MAX_QUEUE_SIZE = 81920000;

    private static final AtomicBoolean initedPool = new AtomicBoolean(false);

    private static final AtomicBoolean initedSinglePool = new AtomicBoolean(false);

    private static final AtomicBoolean initedCachePool = new AtomicBoolean(false);

    private static ExecutorService pool;

    private static ExecutorService signle;

    private static ExecutorService cachePool;

 /**
     * 获取固定大小的Pool.
     *
     * @return ExecutorService
     */
    public static ExecutorService single() {
        if (initedSinglePool.compareAndSet(false, true)) {
            final ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
                    .setNameFormat("scm-single-pool-%d").build();
            signle = MoreExecutors.getExitingExecutorService(new ThreadPoolExecutor(
                    1, 1,
                    0L, TimeUnit.MILLISECONDS,
                    new LinkedBlockingQueue<>(MAX_QUEUE_SIZE),
                    namedThreadFactory, new ThreadPoolExecutor.AbortPolicy()));
        }
        return signle;
    }

    /**
     * 获取固定大小的Pool.
     *
     * @return ExecutorService
     */
    public static ExecutorService fixedPool() {
        if (initedPool.compareAndSet(false, true)) {
            final ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
                    .setNameFormat("scm-pool-%d").build();
            pool = MoreExecutors.getExitingExecutorService(new ThreadPoolExecutor(
                    8, 8,
                    0L, TimeUnit.MILLISECONDS,
                    new LinkedBlockingQueue<>(MAX_QUEUE_SIZE),
                    namedThreadFactory, new ThreadPoolExecutor.AbortPolicy()));
        }
        return pool;
    }

    /**
     * 获取可缓存大小的Pool（0 - 200），每隔60秒销毁多余的Pool.
     *
     * @return
     */
    public static ExecutorService cachePool() {
        if (initedCachePool.compareAndSet(false, true)) {
            final ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
                    .setNameFormat("scm-cachedpool-%d").build();
            cachePool = MoreExecutors.getExitingExecutorService(new ThreadPoolExecutor(
                    20, 512,
                    0L, TimeUnit.SECONDS,
                    new LinkedBlockingQueue<>(MAX_QUEUE_SIZE),
                    namedThreadFactory, new ThreadPoolExecutor.AbortPolicy()));
        }
        return cachePool;
    }

}
